<template>
  <div class="upload-container">
    <input type="file" ref="fileInput" @change="handleFileSelect" />
    <button @click="uploadFile" :disabled="!file || isUploading">
      {{ isUploading ? '上传中...' : '开始上传' }}
    </button>

    <div v-if="progress > 0" class="progress-container">
      <div class="progress-bar" :style="{ width: progress + '%' }">
        {{ progress }}%
      </div>
    </div>

    <div v-if="message" class="message">{{ message }}</div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';

const fileInput = ref(null);
const file = ref(null);
const progress = ref(0);
const isUploading = ref(false);
const message = ref('');

const handleFileSelect = () => {
  file.value = fileInput.value.files[0];
  progress.value = 0;
  message.value = '';
};

const uploadFile = async () => {
  if (!file.value) return;

  isUploading.value = true;
  message.value = '';
  progress.value = 0;

  const formData = new FormData();
  formData.append('file', file.value);

  try {
    const response = await axios.post('http://localhost:5000/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
      onUploadProgress: (progressEvent) => {
        console.log("🚀 ~ uploadFile ~ progressEvent.loaded:", progressEvent.loaded)
        if (progressEvent.total) {
          progress.value = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          );
        }
      }
    });

    message.value = `上传成功！文件名: ${response.data.filename}`;
  } catch (error) {
    message.value = `上传失败: ${error.message}`;
    console.error('上传错误:', error);
  } finally {
    isUploading.value = false;
  }
};
</script>

<style scoped>
.upload-container {
  max-width: 500px;
  margin: 2rem auto;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 8px;
}

input[type="file"] {
  display: block;
  margin-bottom: 15px;
}

button {
  background: #42b983;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
}

button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.progress-container {
  height: 25px;
  background: #f0f0f0;
  border-radius: 4px;
  margin: 15px 0;
  overflow: hidden;
}

.progress-bar {
  height: 100%;
  background: #42b983;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  transition: width 0.3s ease;
}

.message {
  margin-top: 15px;
  padding: 10px;
  border-radius: 4px;
  background: #f8f8f8;
}
</style>